// 生成随机id
export const randomId = () => Math.random().toString(36).substr(2, 10);

/** 显示弹窗
 * @param {string} title 弹窗标题
 * @param {string} icon 弹窗图标
 * @param {string} duration 弹窗持续时间
 * @param {string} mask 是否显示透明蒙层，防止触摸穿透
 * @param {string} image 自定义图标的本地路径，image 的优先级高于 icon
 * @param success 成功回调，默认为空
 * @param fail 失败回调
 * @param complete 完成回调
 */
export const showToast = (
  title: string,
  icon: 'none' | 'success' | 'loading' | 'error' | undefined = 'none',
  duration = 1500,
  mask = false,
  image = '',
  // success默认值是空函数
  success = () => {},
  fail = () => {},
  complete = () => {},
) => {
  uni.showToast({
    title,
    icon,
    duration,
    mask,
    image,
    success,
    fail,
    complete,
  });
};

/** 将canvas临时保存到本地，返回图片地址
 * @param {Vue} component 自定义组件实例
 * @param {string} canvasId canvas的id
 * @param {string} fileType 文件类型，jpg或者png
 * @param {string} quality 图片质量，0-1
 * @param {string} complete 完成回调
 */
export const canvasToTempFilePath = (
  component: Vue,
  canvasId: string,
  fileType: 'jpg' | 'png' = 'jpg',
  quality = 1,
  complete: (res: any) => void,
) => new Promise((resolve, reject) => {
  uni.canvasToTempFilePath(
    {
      canvasId,
      fileType,
      quality,
      success: (res: any) => {
        resolve(res.tempFilePath);
      },
      fail: (err: any) => {
        reject(err);
      },
      complete,
    },
    component,
  );
});

/** 保存图片到系统相册
 * @param {string} filePath 图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
 * @param {string} complete 完成回调
 */
export const saveImageToPhotosAlbum = (
  filePath: string,
  complete: (res: any) => void,
) => new Promise((resolve, reject) => {
  uni.saveImageToPhotosAlbum({
    filePath,
    success: (res: any) => {
      resolve(res);
    },
    fail: (err: any) => {
      reject(err);
    },
    complete,
  });
});

/** 开启分享功能 */
export const showShareMenu = () => {
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline'],
  });
};

/** 申请订阅消息 */
export const requestSubscribeMessage = () => {
  // XXX 临时关闭

};

export const coutupAni = ({
  start = 0,
  end = 100,
  duration = 2,
  fps = 60,
  numDisplay, // 必传 界面上展示的值
}) => {
  const interval = 1000 / fps; // 毫秒
  const delta = (end - start) / (duration * fps); // 每帧变化量
  const animate = () => {
    // 更新数字
    start += delta;
    numDisplay.value = Math.round(start);
    // 判断是否达到目标值，如果没有则继续调用定时器函数
    if (start < end) {
      setTimeout(animate, interval);
    } else {
      // 如果达到目标值，停止定时器并显示最终结果
      numDisplay.value = end;
    }
  };
  animate();
};

/** 判断当前时间是否在启始时间和结束时间之间 */
export const isBetweenTime = (startTime: string, endTime: string) => {
  const now = new Date();
  const start = new Date(startTime);
  const end = new Date(endTime);
  if (now.getTime() > start.getTime() && now.getTime() < end.getTime()) {
    return true;
  }
  return false;
};

/**
 * 格式化html字符串，给所有常见的标签都添加对应的类名
 * @param {string} html html字符串
 * @return {string} 格式化后的html字符串
 */
export const addClassToHtml = (html: string) => {
  // 要替换的标签
  const tags = [
    'p',
    'span',
    'div',
    'img',
    'a',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'table',
    'thead',
    'tbody',
    'tr',
    'th',
    'td',
    'ul',
    'ol',
    'li',
    'dl',
    'dt',
    'dd',
  ];

  // 遍历所有标签
  tags.forEach((tag) => {
    // 匹配标签的正则表达式
    const reg = new RegExp(`<${tag}([^>]*)>`, 'g');
    // 替换标签
    html = html.replace(reg, `<${tag} class="rich-${tag}" $1>`);
  });

  return html;
};

// 模板消息
const TEMPLATEMSGS: TempItem[] = [
  {
    txt: 'judge_fail',
    key: 'ztGzdO9aY5kgo-PLkUJ1CMFh-9pOlRZSPJsvz0kbbpA',
  },
  {
    txt: 'judge_success',
    key: 'iXnLiAvjq4EEarieM0vqBnBoOXWfdZgJhw6GtV3JxYU',
  },
];
/** 嗨喵互动分享季订阅模版消息 */
export const requestSubscribeMessageSpsj = () => {
  const target = TEMPLATEMSGS.map((item) => item.key);
  uni.requestSubscribeMessage({ tmplIds: [...target] });
  // 更新弹出时间
  uni.setStorageSync('tmpTime', getCurrentTime());
};

/** 获取当前时间 */
export const getCurrentTime = () => {
  const date = new Date();
  // 获取完整的年份 (4位)
  const year: any = date.getFullYear();
  // 获取当前月份 (0-11,0代表1月)
  let month: any = date.getMonth() + 1;
  // 获取当前日 (1-31)
  let strDate: any = date.getDate();
  // 如果月份是个位数，在前面补0
  if (Number(month) < 10) month = `0${month}`;
  // 如果日是个位数，在前面补0
  if (Number(strDate) < 10) strDate = `0${strDate}`;
  return `${year}-${month}-${strDate}`;
};
